package com.aplink.generic.util;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Utility {

    private static int countSampleValue( int originalWidth, int originalHeight,
                                         int newWidth, int newHeight ) {
        int sample = 1;

        // prevent loop cycle in case our parameter is smaller than 0
        if ( ( originalWidth <= 0 ) || ( originalHeight <= 0 ) || ( newWidth <= 0 )
                || ( newHeight <= 0 ) ) {
            return sample;
        }

        while ( ( ( originalWidth >> 1 ) > newWidth )
                || ( ( originalHeight >> 1 ) > newHeight ) ) {

            sample <<= 1;
            originalWidth >>= 1;
            originalHeight >>= 1;

        }

        return sample;
    }

    public static String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.getDefault() );
        Date date = new Date();
        return dateFormat.format( date );
    }

    public static String formatDatetime( Date date ) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.getDefault() );
        return dateFormat.format( date );
    }

    public static Date parseDatetime( String datetime ) {
        SimpleDateFormat dateFormat = null;
        try {
            dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss",
                    Locale.getDefault() );
            return dateFormat.parse( datetime );
        } catch ( ParseException e ) {
            dateFormat = new SimpleDateFormat( "dd/MM/yyyy HH:mm:ss a",
                    Locale.getDefault() );
            try {
                return dateFormat.parse( datetime );
            } catch ( ParseException e1 ) {
                e1.printStackTrace();
            }
        }
        return null;
    }

    public static String formatDateTime( Date date, String format ) {
        SimpleDateFormat dateFormat = new SimpleDateFormat( format,
                Locale.getDefault() );
        return dateFormat.format( date );
    }

    public static Options getBitmapOption( Context context, URL url )
            throws IOException {

        final int widthpixel = context.getResources().getDisplayMetrics().widthPixels;
        final int heightpixel = context.getResources().getDisplayMetrics().heightPixels;

        final Options o = new Options();

        // just decoding the boundary no actually image streaming
        o.inJustDecodeBounds = true;

        final InputStream is = url.openStream();

        BitmapFactory.decodeStream( is, null, o );

        // get actual width x height of the image and calculate the scale
        // factor
        o.inSampleSize = countSampleValue( o.outWidth, o.outHeight, widthpixel,
                heightpixel );

        is.close();

        o.inJustDecodeBounds = false;

        return o;
    }

    public static String myURLencode( String input ) {
        String output = input;

        output = output.replaceAll( " ", "%20" );

        return output;
    }

    public static void syncDownload( final String urlImage,
                                     final AsyncTask<String, ?, ?> taskExcuteOnComplete ) {

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground( Void... params ) {

                try {
                    final URL url = new URL( urlImage );
                    final InputStream input = url.openStream();
                    try {

                        final File storagePath = new File( Environment
                                .getExternalStorageDirectory()
                                .getAbsolutePath(), "SellProff" );

                        storagePath.mkdirs();

                        final String temporaryName = String.format(
                                Locale.getDefault(), "%d.jpg",
                                System.currentTimeMillis() );

                        final File pathURL = new File( storagePath,
                                temporaryName );

                        final OutputStream output = new FileOutputStream(
                                pathURL );

                        System.out.println( ">>>> path = " + pathURL.toString() );
                        try {
                            final byte[] buffer = new byte[1024];
                            int bytesRead = 0;
                            while ( ( bytesRead = input.read( buffer, 0,
                                    buffer.length ) ) >= 0 ) {
                                output.write( buffer, 0, bytesRead );
                            }

                            return "file://" + pathURL.toString();
                        } finally {
                            output.close();
                        }
                    } finally {
                        input.close();
                    }
                } catch ( final Exception e ) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute( String filePath ) {

                if ( filePath != null ) {
                    if ( taskExcuteOnComplete != null ) {
                        taskExcuteOnComplete.execute( filePath );
                    }
                }
            }
        }.execute();
    }
}
